package com.services
{
	import com.model.ItemChooser;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.utils.ArrayUtil;
	
	public class GetCoursesService extends BasicService
	{
		public var courses: ArrayCollection;
		
		public function GetCoursesService(busyCursor:Boolean=false, callBack:Function=null)
		{
			var url:String = IslamicBook.BACKEND_URL + "courses.xml";
			super(url, "GET", busyCursor, callBack);
			service.requestTimeout = 30;
			send();
		}
		
		override public function resultHandler(event:ResultEvent):void
		{
			if(event.result.courses && event.result.courses.course != null) {
				if(event.result.courses.course != null)	{
					var courses: ArrayCollection = 
						event.result.courses.course is ArrayCollection ?
						event.result.courses.course : new ArrayCollection(ArrayUtil.toArray(event.result.courses.course));
					constructBooks(courses);
				}
			}else if (event.result.course) {
				var obj:Object = event.result.book; 
				this.courses = new ArrayCollection();
				this.courses.addItem(new ItemChooser(obj.name.valueOf(), obj.id.valueOf()));					
			}
			
			super.resultHandler(event);
		}
		
		private function constructBooks(items:ArrayCollection):void
		{
			this.courses = new ArrayCollection();
			for(var i:int = 0; i < items.length; i++)
			{
				this.courses.addItemAt(new ItemChooser(items[i].name.valueOf(), items[i].id.valueOf()),0);
			} 
		}	
		
		override public function faultHandler(event:FaultEvent):void
		{
			Alert.show(event.toString());
		}
	}
}